package com.example.video.service;

import com.example.video.domain.Device;
import com.example.video.repository.DeviceInformationRepository;
import com.example.video.repository.DeviceRepository;
import com.example.video.service.inter.IDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class DeviceServiceImpl implements IDeviceService {

    private final DeviceRepository deviceRepository;
    private final DeviceInformationRepository deviceInformationRepository;

    @Autowired
    public DeviceServiceImpl(DeviceRepository deviceRepository, DeviceInformationRepository deviceInformationRepository) {
        this.deviceRepository = deviceRepository;
        this.deviceInformationRepository = deviceInformationRepository;
    }

    @Override
    public void addOrUpdateDevice(Device device) {
        deviceRepository.saveAndFlush(device);
    }

    @Override
    @Transactional
    public void deleteDevices(List<Long> deviceIds) {
        for (Long id : deviceIds) {
            deviceInformationRepository.deleteByPk_Device_Id(id);
            deviceRepository.deleteById(id);
        }
    }

    @Override
    public List<Device> getDeviceList(int page, int size) {
        return deviceRepository.findAll(PageRequest.of(page, size)).getContent();
    }
}
